// pages/order/index.js
import {queryAllOrder} from '../../request/order'
Page({
  data: {
    tabs: [
      {id: 0, value: '全部', isActive: true},
      {id: 1, value: '待付款', isActive: false},
      {id: 2, value: '待发货', isActive: false},
      {id: 3, value: '退款/退货', isActive: false},
    ],
    orders: []
  },
  onLoad (options) {
    const token = wx.getStorageSync("token");
    if (!token) {
     wx.navigateTo({
        url: '/pages/auth/index'
      });
      return;
    }
    //1.获取当前的小程序的页面栈-数组，最大长度是10页面（回退页面最多10页）
    let pages = getCurrentPages();
    //2.数组中，索引最大的页面就是当前页面
    let currentPage = pages[pages.length - 1];
    // console.log(currentPage.options);
    //3.获取url上的type参数
    const { type } = currentPage.options;
    //4.激活选中页面标题index=type-1
    this.changeTitleByIndex(type - 1);
    this.getAllOrder(type);
  },
  //根据标题索引来激活选择 标题数组
  changeTitleByIndex(index) {
    //2.修改原数组
    let { tabs } = this.data
    tabs.forEach((v, i) => i === index ? v.isActive = true : v.isActive = false);
    //3.赋值到data中
    this.setData({
      tabs
    })
  },
  /* tab栏切换 */
  handleTabsItemChange (e) {
    const {index} = e.detail
    this.changeTitleByIndex(index)
    this.getAllOrder(index + 1)
  },

  /* 查询所有订单 */
  async getAllOrder (type) {
    const {orders} = await queryAllOrder(type)
    this.setData({
      orders: orders.map(v => ({ ...v, create_time_cn: (new Date(v.create_time * 1000).toLocaleString()) }))
    })
  }
})